import logging
import imaplib

from routes.util import url_for

from pymomail.lib.base import *
from pymomail.lib.mailstore import *

log = logging.getLogger(__name__)

class FolderController(BaseController):
    _M = None

    def __init__(self):
        self._M = MailStoreFactory(config['imap_url'])

    def _do_login(self):
        #print "trying user %s" % ''.join([session['username'], session['domain']])
        self._M.login(''.join([session['username'], session['domain']]), session['password'])

    def _require_login(self):
        response.headers['Content-type'] = 'text/vnd.wap.wml'
        try:
            self._do_login()
        except KeyError:
            return redirect_to(url_for('login'))
        except:
            return render('/wml/403.mako')

    def children(self, fname='INBOX'):
        self._require_login()
        folder = self._M.open(fname)
        c.folder = folder
        c.folders = folder.children()
        ret = render('/wml/subfolders.mako')
        self._M.logout()
        return ret

    def view(self, fname='INBOX'):
        self._require_login()
        try:
            page = int(request.params['page'])
        except:
            page = 1

        count = 5
        start = count * (page - 1)

        folder = self._M.open(fname)
        c.folder = folder
        c.messages_total = folder.total()

        # No use for a reload just for a few messages.
        # If all the messages would fit on two screens, return them all
        if c.messages_total <= count * 2:
            count = count * 2

        c.messages_start = start + 1
        c.messages_end = min(start + count, c.messages_total)
        if page > 0:
            c.messages_prev = page - 1
        if start + count < c.messages_total:
            c.messages_next = page + 1

        c.messages = folder.messages(start,count)
        c.folders = folder.children()
        ret = render('/wml/folder.mako')
        self._M.logout()
        return ret
    
    def index(self, fname='INBOX'):
        self._require_login()
        folder = self._M.open(fname)
        c.folder = folder
        ret = render('/wml/folder.mako')
        self._M.logout()
        return ret
